// Vue CLI3搭建组件库并实现按需引入实战操作
// https://juejin.cn/post/6844904000655998984?searchId=202401231545165476C969F18E7E762FE4

// const { defineConfig } = require("@vue/cli-service");
// const compPath = require("./components.json");
// console.log("compPath: ", compPath);
// module.exports = defineConfig({
//   transpileDependencies: true,
//   lintOnSave: false, //关闭语法检查
// });

const fs = require("fs");
const path = require("path");
const resolve = (dir) => path.resolve(__dirname, dir);

const join = path.join;
function getEntries(path) {
  let files = fs.readdirSync(resolve(path));
  const entries = files.reduce((ret, item) => {
    const itemPath = join(path, item);
    const isDir = fs.statSync(itemPath).isDirectory();
    if (isDir) {
      ret[item] = resolve(join(itemPath, "index.js"));
    } else {
      const [name] = item.split(".");
      ret[name] = resolve(`${itemPath}`);
    }
    return ret;
  }, {});
  return entries;
}
//开发环境配置
const devConfig = {
  pages: {
    index: {
      entry: "src/main.js",
      template: "public/index.html",
      filename: "index.html",
    },
  },
  configureWebpack: {
    resolve: {
      extensions: [".js", ".vue", ".json"],
      alias: {
        "@": resolve("src"),
        assets: resolve("src/assets"),
        views: resolve("src/views"),
      },
    },
  },
  chainWebpack: (config) => {
    config.module
      .rule("js")
      .include.add("/src/packages")
      .end()
      .use("babel")
      .loader("babel-loader")
      .tap((options) => {
        return options;
      });
  },
  devServer: {
    port: 8091,
    hot: true,
    open: "Google Chrome",
  },
};
//生成环境配置
const buildConfig = {
  css: {
    sourceMap: true,
    extract: {
      filename: "style/[name].css",
    },
  },
  configureWebpack: {
    entry: {
      ...getEntries("src/packages"),
    },
    output: {
      filename: "[name]/index.js",
      libraryTarget: "commonjs2",
    },
  },
  chainWebpack: (config) => {
    config.module
      .rule("js")
      .include.add("/packages")
      .end()
      .use("babel")
      .loader("babel-loader")
      .tap((options) => {
        return options;
      });
    config.optimization.delete("splitChunks");
    config.plugins.delete("copy");
    config.plugins.delete("html");
    config.plugins.delete("preload");
    config.plugins.delete("prefetch");
    config.plugins.delete("hmr");
    config.entryPoints.delete("app");

    // config.module
    //   .rule("fonts")
    //   .use("url-loader")
    //   .tap((option) => {
    //     option.fallback.options.name = "static/fonts/[name].[hash:8].[ext]";
    //     return option;
    //   });
  },
  outputDir: "lib",
  productionSourceMap: false,
};

module.exports =
  process.env.NODE_ENV === "development" ? devConfig : buildConfig;
